﻿using Inovout.Runtime;
using System.Linq;
using System.Net.Http;
using System.Security.Principal;
using System.Threading;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Routing;


namespace Inovout.Web.Http
{
    public class BaseHttpController : ApiController
    {
        public IApplication Application { get; private set; }
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            Application = ComponentRegistry.Resolve<IApplication>();
            base.Initialize(controllerContext);
            Initialize();
            OnAuthorization();
        }
        protected virtual void Initialize()
        {
        }
        protected virtual void OnAuthorization()
        {
            OnAuthorizationAs(Inovout.Security.UserPrincipal.AnonymousUserPrincipal);
        }
        protected void OnAuthorizationAs(IPrincipal user)
        {
            HttpContext.Current.User = Thread.CurrentPrincipal = user;
        }
        protected object GetParameterValue(string parameterName)
        {
            object parameterValue;
            TryGetParameterValue(parameterName, out parameterValue);
            return parameterValue;
        }
        protected bool TryGetParameterValue(string parameterName, out object parameterValue)
        {
            var routeData = base.ControllerContext.RouteData.GetMergeRoutes();
            if (!routeData.Values.TryGetValue(parameterName, out parameterValue))
            {
                if (base.ControllerContext.Request.Headers.Contains(parameterName))
                {
                    parameterValue = base.ControllerContext.Request.Headers.GetValues(parameterName).ToArray()[0];
                }
                else if (base.ControllerContext.Request.GetQueryNameValuePairs().Any(kv => kv.Key.Equals(parameterName)))
                {
                    parameterValue = base.ControllerContext.Request.GetQueryNameValuePairs()
                        .Single(kv => kv.Key.Equals(parameterName)).Value;
                }
            }
            return parameterValue != null;
        }
    }
}
